/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.max.oti.system.bean.sppp;

import com.max.oti.system.bean.IndexLoginBean;
import com.max.oti.system.model.Company;
import com.max.oti.system.model.FunctionPractice;
import com.max.oti.system.model.HistoryPractice;
import com.max.oti.system.model.Practice;
import com.max.oti.system.service.interfac.ICompanyService;
import com.max.oti.system.service.interfac.IPracticeService;
import com.max.oti.system.util.Clazz;
import com.max.oti.system.util.FacesUtil;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import org.primefaces.event.SelectEvent;

/**
 *
 * @author max
 */
@ManagedBean
@SessionScoped
public class NewPracticeBean {

    @ManagedProperty("#{practiceService}")
    IPracticeService practiceService;
    @ManagedProperty("#{companyService}")
    ICompanyService companyService;
    @ManagedProperty("#{clazz}")
    Clazz clazz;
    @ManagedProperty("#{indexLoginBean}")
    IndexLoginBean indexLoginBean;
    //////////////////PARA LA VISTA///////////////////////
    private Practice practice = new Practice();
    private FunctionPractice functionPractice = new FunctionPractice();
    private List<Company> listCompany;
    private String detailHistoryPractice;
    /////////////////PARA REGISTRAR COMPAÑIA////////////
    private Company company = new Company();
    ////////////////////////////////////////////////////
    private boolean isEdit;

    public void initBean() {
        try {
            indexLoginBean.setNavigation("./content/new_practice.xhtml");
            System.out.println("Cargando datos");
            listCompany = companyService.listHQL("select c.id as id, c.name as name, c.representative as representative from Company c", Company.class);
            practice = new Practice();
            functionPractice = new FunctionPractice();
            company = new Company();
            isEdit = false;
        } catch (Exception ex) {
            Logger.getLogger(NewPracticeBean.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void initBeanEdit() {
        try {
            System.out.println("Cargando datos");
            listCompany = companyService.listHQL("select c.id as id, c.name as name, c.representative as representative from Company c", Company.class);
            functionPractice = new FunctionPractice();
            isEdit = true;
        } catch (Exception ex) {
            Logger.getLogger(NewPracticeBean.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    public void newCompany() {
        company = new Company();
    }
    public void createFunction() {
        System.out.println("createFunction: Entrando a crear una nueva funcion...");
        functionPractice = new FunctionPractice();

    }

    public void searchPracticeInWebService() {
        //OPRACION DE BUSCAR EN EL WEB SERVICE
//        if( WS no trajo nada ){
//            namePractice = null;
//            credit = null;
//        } else {
//            namePractice = WS.name;
//            credit = WS.credit;
//        }
        practice.setNames("Nombre del practicante");
        practice.setCredit(161);
    }
    
    public void removeFunctionOfPractice(FunctionPractice function) {
        System.out.println("removeFunctionOfPractice: " + function.getDetail());
        practice.getFunctionPracticeList().remove(function);
        FacesUtil.addMessage("Debe Guardar al finalizar", null, FacesMessage.SEVERITY_INFO);
    }

    public void handleDateSelect(SelectEvent event) {
        Date dateTemp = (Date) event.getObject();
        dateTemp.setMonth(dateTemp.getMonth() + 3);
        practice.setEndDate(dateTemp);
    }

    public void saveOrUpdatePractice() {
        if (practice.getId() == null) {
            try {
                if (practice.getCodeAlumn().startsWith("00") && practice.getCodeAlumn().length() == 10
                        && practice.getNames() != null && !practice.getNames().isEmpty() && practice.getCredit() >= 160) {
                       
                    System.out.println("Guardando");

                    HistoryPractice hp = new HistoryPractice();
                    hp.setDate(new Date());
                    hp.setDetail(detailHistoryPractice);
                    hp.setDocumentFormal("*");
                    hp.setIdPractice(practice);
                    hp.setOldHistory(false);
                    hp.setIdState(clazz.STATE(Clazz.STATE.Name.INSCRIPCION_DE_PRACTICAS, Clazz.STATE.Entity.HISOTRY_PRACTICE));

                    practice.getHistoryPracticeList().add(hp);
                    practiceService.save(practice);

                    practice = new Practice();
                    functionPractice = new FunctionPractice();
                    detailHistoryPractice = null;
                    FacesUtil.getRequestContext().execute("confirmPractice.hide();");
                    FacesUtil.addMessage("Guardado con éxito...", null, FacesMessage.SEVERITY_INFO);
                } else {
                    FacesUtil.getRequestContext().execute("confirmPractice.hide();");
                    FacesUtil.addMessage("ALUMNO NO ENCONTRADO O CREDITOS MENOR A 160.", null, FacesMessage.SEVERITY_WARN);
                }
            } catch (Exception ex) {
                Logger.getLogger(PracticeBean.class.getName()).log(Level.SEVERE, null, ex);
            }
        } else {
            try {
                if (practice.getHistoryPracticeList() != null && !practice.getHistoryPracticeList().isEmpty()) {
                    practice.getHistoryPracticeList()
                            .get(0)
                            .setDetail(detailHistoryPractice);
                }
                System.out.println("Actualizar");
                practiceService.saveOrUpdate(practice);
                practice = new Practice();
                functionPractice = new FunctionPractice();
                detailHistoryPractice = "";
                FacesUtil.getRequestContext().execute("confirmPractice.hide();");
                FacesUtil.addMessage("Actualizado con éxito...", null, FacesMessage.SEVERITY_INFO);

            } catch (Exception ex) {
                Logger.getLogger(PracticeBean.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    public void saveCompany() {
        if (company.getId() == null) {
            try {
                companyService.save(company);
                FacesUtil.addMessage("Registro con Éxito", null, FacesMessage.SEVERITY_INFO);
                listCompany.add(company);
                company = new Company(); //resetear campos

            } catch (Exception ex) {
                Logger.getLogger(CompanyBean.class.getName()).log(Level.SEVERE, null, ex);
                FacesUtil.addMessage("Error en el Registro", null, FacesMessage.SEVERITY_ERROR);
            }
        } else {
            try {
                companyService.update(company);
                FacesUtil.addMessage("Actualizado con Éxito", null, FacesMessage.SEVERITY_INFO);
                company = new Company(); //resetear campos
                listCompany = companyService.listHQL("select c.id as id, c.name as name, c.representative as representative from Company c", Company.class);
            } catch (Exception ex) {
                Logger.getLogger(CompanyBean.class.getName()).log(Level.SEVERE, null, ex);
                FacesUtil.addMessage("Error en el Registro", null, FacesMessage.SEVERITY_ERROR);
            }
        }
    }

    public void addFunctionToPractice() {
        System.out.println("Entrado a guardar una funcion");
        System.out.println("Detalle de funcion:" + functionPractice.getDetail());
        System.out.println(practice);
        System.out.println("total de funcones: " + practice.getFunctionPracticeList().size());
        functionPractice.setIdPractice(practice);
        functionPractice.setNumber(practice.getFunctionPracticeList().size() + 1);

        practice.getFunctionPracticeList().add(functionPractice);
        functionPractice = new FunctionPractice();
    }

//<editor-fold defaultstate="collapsed" desc="Getter and Setter">
    public Practice getPractice() {
        return practice;
    }

    public boolean isIsEdit() {
        return isEdit;
    }

    public IndexLoginBean getIndexLoginBean() {
        return indexLoginBean;
    }

    public void setIndexLoginBean(IndexLoginBean indexLoginBean) {
        this.indexLoginBean = indexLoginBean;
    }

    public void setIsEdit(boolean isEdit) {
        this.isEdit = isEdit;
    }

    public Company getCompany() {
        return company;
    }

    public void setCompany(Company company) {
        this.company = company;
    }

    public void setClazz(Clazz clazz) {
        this.clazz = clazz;
    }

    public void setPracticeService(IPracticeService practiceService) {
        this.practiceService = practiceService;
    }

    public void setPractice(Practice practice) {
        this.practice = practice;
    }

    public String getDetailHistoryPractice() {
        return detailHistoryPractice;
    }

    public void setDetailHistoryPractice(String detailHistoryPractice) {
        this.detailHistoryPractice = detailHistoryPractice;
    }

    public FunctionPractice getFunctionPractice() {
        return functionPractice;
    }

    public void setFunctionPractice(FunctionPractice functionPractice) {
        this.functionPractice = functionPractice;
    }

    public void setCompanyService(ICompanyService companyService) {
        this.companyService = companyService;
    }

    public List<Company> getListCompany() {
        return listCompany;
    }

    public void setListCompany(List<Company> listCompany) {
        this.listCompany = listCompany;
    }
    //</editor-fold>
}
